﻿using System;
using System.Collections.Generic;
using System.Text;
using TTClassLibrary;
using TTServer.Messages;
using libCommonClass;
using TTServer.Controller;
using libAsymmetricEncryption;
using libUtilities;

namespace TTServer.MessageProcessor
{
    public class KeyMemberAuthentificationRequestMessageProcessor : IMessageProcessor
    {
        public bool Process(libCommonClass.TTMessage message, libInterface.IClientInfoProvider clientInfoProvider)
        {
            if (message is KeyMemberAuthentificationRequestMessage)
            {
                KeyMemberAuthentificationResponseMessage response = null;
                AuthenManagement am = AuthenManagement.getInstance();
                if (am.isKeyMemberAuthenticated)
                {
                    //fail because there has been already Key member logined
                    response = new KeyMemberAuthentificationResponseMessage(2, new byte[1]);
                }
                else
                {
                    KeyMemberAuthentificationRequestMessage msg = (KeyMemberAuthentificationRequestMessage)message;

                    byte[] encryptedPassword = msg.encryptedPassword;

                    byte[] decryptedPassword = RSA_Algorithm.rsaDecryptWithPrivateKey(
                        RSA_KeyManager.getInstance().privateParameters, encryptedPassword);

                    string strPassword = System.Text.Encoding.Unicode.GetString(decryptedPassword);

                    String pass = am.CurrentActiveGroup.Password;

                    if (pass.Equals(strPassword) == true) // need change this line
                    {
                        clientInfoProvider.Authority = AuthorityConstant.KEY_MEMBER;

                        clientInfoProvider.TemporaryKey = OtherUtils.GenerateTemporaryKey();

                        byte[] dataToBeEncrypted = System.Text.Encoding.Unicode.GetBytes(clientInfoProvider.TemporaryKey);

                        byte[] encrypteddata = RSA_Algorithm.rsaEncryptWithPublicKey(
                            clientInfoProvider.ClientPublicKey, dataToBeEncrypted);

                        //successfully
                        response = new KeyMemberAuthentificationResponseMessage(1, encrypteddata);
                        AuthenManagement.getInstance().isKeyMemberAuthenticated = true;
                    }
                    else
                    {
                        //fail because enter wrong password
                        response = new KeyMemberAuthentificationResponseMessage(0, new byte[1]);
                    }
                }

                if (response != null)
                {
                    clientInfoProvider.AddToMessageQueue(response);
                }

                return true;
            }

            return false;
        }
    }
}
